import requests
import json
# 1.新建一个会话，打招呼
url = "https://qianfan.baidubce.com/v2/app/conversation"
app_id="ff553b09-58ba-4a76-85da-55e12a9ffd02"
payload = json.dumps({
    "app_id": "ff553b09-58ba-4a76-85da-55e12a9ffd02"
})

headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': 'Bearer bce-v3/ALTAK-onfFjTUrNsxSCTMRO1uSP/8a9f0b30ec96f74717c91cf081ad8d77cb7b71d6'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
conversation_id = json.loads(response.text)['conversation_id']
if not conversation_id:
        print("Failed to get conversation_id")
        exit(1)
# 2.问答请求
url = "https://qianfan.baidubce.com/v2/app/conversation/runs"

query = input("请输入问题：")
payload = json.dumps({
    "app_id": app_id,
    # 自己输出
    "query": query,
    "stream": False,
    # 从上一次请求中获取
    "conversation_id": conversation_id
})
headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': 'Bearer bce-v3/ALTAK-onfFjTUrNsxSCTMRO1uSP/8a9f0b30ec96f74717c91cf081ad8d77cb7b71d6'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
# todo-1：只打印answer
result = json.loads(response.text)["results"]
for item in result:
    print(item["answer"])
#
# todo-2：将问题答案存入txt
with open('./answer.txt', 'w') as f:
    for item in result:
        f.write(item["answer"] + '\n')
        f.close()
    print("文件写入成功")
 # 上传文件
    url = "https://qianfan.baidubce.com/v2/app/conversation/file/upload"
    payload = {
        'app_id': app_id,
        'conversation_id': conversation_id
    }
    files = [
        ('file', ('answer.txt', open("answer.txt", 'rb'), 'text/plain'))
    ]
    headers = {
        'X-Appbuilder-Authorization': bearer
    }
    
    response = requests.request("POST", url, headers=headers, data=payload, files=files)

    upload_response_data = json.loads(response.text)
    
    uploaded_file_id = upload_response_data.get('file_id')  # 根据实际响应调整字段名
    if uploaded_file_id:
        print("上传成功：", uploaded_file_id)
    else:
        print("上传失败")
    
    # 输出文件内容
    with open('answer.txt', 'r', encoding='utf-8') as file:
        lines = file.readlines()
        for line in lines:
            print(line, end='')